package cn.lsg.util;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import org.im4java.core.ConvertCmd;
import org.im4java.core.IM4JavaException;
import org.im4java.core.IMOperation;
import org.im4java.core.IMOps;
import org.im4java.core.IdentifyCmd;

import org.im4java.process.ArrayListOutputConsumer;

/**
 * 图片处理
 * <p>
 * im4java-1.2.1.jar <br />
 * GraphicsMagick-1.3.12-Q16
 * </p>
 */
public class UtilImage {
	private final static boolean GraphicsMagick = false;
	// linux 系统 graphicsMagick bin目录
	private final static String MagickBaseDir = "/usr/local/work/runsoft/ImageMagick/bin";

	/**
	 * 图片尺寸
	 * 
	 * @param file
	 *            图片文件
	 * @return Map("w","h") 图片大小
	 * @throws Exception
	 */
	public synchronized static HashMap<String, Integer> getSize(File file)
			throws Exception {
		HashMap<String, Integer> map = new HashMap<String, Integer>();
		IMOperation op = new IMOperation();
		op.format("%w,%h");
		op.addImage(1);
		IdentifyCmd identifyCmd = new IdentifyCmd(GraphicsMagick);
		if (!GraphicsMagick) {
			identifyCmd.setSearchPath(MagickBaseDir);
		}
		ArrayListOutputConsumer output = new ArrayListOutputConsumer();
		identifyCmd.setOutputConsumer(output);
		identifyCmd.run(op, file.getPath());
		ArrayList<String> cmdOutput = output.getOutput();
		String[] size = cmdOutput.get(0).split(",");
		map.put("w", Integer.parseInt(size[0]));
		map.put("h", Integer.parseInt(size[1]));
		return map;
	}

	/**
	 * 图片居中侧切
	 * 
	 * @param srcPath
	 *            源图片绝对路径
	 * @param desPath
	 *            释出图片绝对路径
	 * @param w
	 *            宽度
	 * @param h
	 *            高度
	 * @throws Exception
	 */
	public synchronized static void cropImageCenter(String srcPath,
			String desPath, int w, int h) throws Exception,
			InterruptedException, IM4JavaException {
		try {
			IMOperation op = new IMOperation();
			op.addImage();
			op.resize(w, h, '^').gravity("center").extent(w, h);
			op.addImage();
			createConvertCmd().run(op, srcPath, desPath);
		} catch (Exception e) {
			throw new Exception("图片处理异常：" + e.getMessage());
		}
	}

	/**
	 * 图片缩放
	 * 
	 * @param srcPath
	 *            源图片绝对路径
	 * @param desPath
	 *            释出图片绝对路径
	 * @param w
	 *            宽度
	 * @param h
	 *            高度
	 * @throws Exception
	 */
	public synchronized static void zoomImage(String srcPath, String desPath,
			Integer w, Integer h) throws Exception {

		IMOps op = new IMOperation();
		op.addImage(srcPath);
		op.resize(w, h);
		op.addImage(desPath);
		File file = new File(desPath);
		file.delete();
		createConvertCmd().run(op);
	}

	/**
	 * 创建命令转换
	 * 
	 * @return ConvertCmd 转换命令
	 */
	private synchronized static ConvertCmd createConvertCmd() {
		ConvertCmd convert = new ConvertCmd(GraphicsMagick);
		if (!GraphicsMagick) {
			convert.setSearchPath(MagickBaseDir);
		}
		return convert;
	}

}
